package com.dtease.agent.core.mybatis.datasource;

import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import com.zaxxer.hikari.HikariDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;

/**
 * @description agent-store 数据源配置
 * @author chentl
 * @class AgentStoreDataSourceConfig
 * @package com.dtease.agent.metadata.config
 * @since 2025/5/7 15:42
 */
@Configuration
@MapperScan(basePackages = {"com.dtease.agent.biz.agentstore.mapper", "com.dtease.agent.biz.ai.mapper"},
        sqlSessionFactoryRef = "agentStoreSqlSessionFactory")
public class AgentStoreDataSourceConfig {

    /**
     * agent-store 数据源配置 | 主源
     *
     * @return DataSource
     */
    @Primary
    @Bean(name = "agentStoreDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.agent-store")
    public DataSource agentStoreDataSource() {
        return DataSourceBuilder.create()
                .type(HikariDataSource.class)
                .build();
    }

    @Primary
    @Bean("agentStoreSqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("agentStoreDataSource") DataSource dataSource, MybatisPlusInterceptor mybatisPlusInterceptor) throws Exception {
        MybatisSqlSessionFactoryBean sessionFactory = new MybatisSqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        sessionFactory.setPlugins(mybatisPlusInterceptor);
        return sessionFactory.getObject();
    }

    @Primary
    @Bean("agentStoreTransactionManager")
    public PlatformTransactionManager transactionManager(@Qualifier("agentStoreDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
}